package com.emperor.service.impl;

import com.emperor.constant.MessageConstant;
import com.emperor.dto.UserLoginDto;
import com.emperor.entity.Partner;
import com.emperor.entity.User;
import com.emperor.mapper.UserMapper;
import com.emperor.service.UserService;
import com.emperor.vo.SkuClassPageVo;
import com.emperor.vo.UserIdVo;
import com.emperor.vo.UserPageVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDto userLoginDto)  {
        String password = userLoginDto.getPassword();
        //1、根据用户名查询数据库中的数据

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        userLoginDto.setPassword(password);
        User login = userMapper.login(userLoginDto);


        //3、返回实体对象
        return login;
    }

    @Override
    public UserIdVo getUser(Integer id) {
        UserIdVo userIdVo = new UserIdVo();
        User user = userMapper.getUser(id);
        BeanUtils.copyProperties(user,userIdVo);
        return userIdVo;
    }

    @Override
    public SkuClassPageVo findAll(Integer pageIndex, Integer pageSize, String name) {
        //设置分页信息
        PageHelper.startPage(pageIndex, pageSize);
        //调用查询所有数据的方法
        List<UserPageVO> list = userMapper.findAll(name);
        //将查询到的数据封装到Page中
        Page<UserPageVO> p = (Page<UserPageVO>) list;
        //计算总页数
        long l = (p.getTotal() / pageSize) + 1;
        //封装返回结果
        SkuClassPageVo build = SkuClassPageVo.builder().
                pageIndex(pageIndex).
                pageSize(pageSize)
                .totalPage((int) l).totalCount((int) p.getTotal())
                .currentPageRecords(new List[]{p.getResult()}).build();
        //返回封装结果
        return build;
    }

    @Override
    public void save(User user) {
        userMapper.save(user);
    }

    @Override
    public void updateById(Integer userId, User user) {
        userMapper.updateById(userId,user);
    }

    @Override
    public void deleteById(Integer userId) {
        userMapper.deleteById(userId);
    }
}
